﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Liya.Crm.Web.Models;
using Liya.Crm.Data.Models;
using Liya.Crm.IService;
using Liya.Crm.Utility;
using System.Web.Security;

namespace Liya.Crm.Web.Controllers
{
    public class UserInfoController : BaseController
    {
        protected IUserInfo _userInfoService;
        protected IRoleUser _roleUserService;

        public UserInfoController(IUserInfo userInfoService, IRoleUser roleUserService)
        {
            _userInfoService = userInfoService;
            _roleUserService = roleUserService;
        }
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Login(LoginModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                Sys_UserInfo user = _userInfoService.UserLogin(model.UserName, EncryptHelper.GetMD5(model.Password));
                if (user != null)
                {
                    UserData userData = new UserData();
                    userData.Roles = new List<int>();
                    userData.UserId = user.UId;
                    userData.DepartmentId = user.UDepartID.Value;
                    userData.UserName = user.UUserName;
                    userData.TrueName = user.UTrueName;

                    //获取用户角色
                    IList<Sys_RoleUser> roles = _roleUserService.GetRolesByUser(user.UId);
                    if (roles != null)
                    {
                        userData.Roles = (from r in roles
                                          select r.RURoleId).ToList();
                    }

                    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                        1,
                        user.UUserName,
                        DateTime.Now,
                        DateTime.Now.Add(FormsAuthentication.Timeout),
                        model.RememberMe,
                        JsonHelper.JsonSerializer<UserData>(userData)
                        );
                    CookieHelper.SetObject(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket));
                    //HttpCookie cookie = new HttpCookie(
                    //    FormsAuthentication.FormsCookieName,
                    //    FormsAuthentication.Encrypt(ticket));
                    //Response.Cookies.Add(cookie);

                    if (!String.IsNullOrEmpty(returnUrl)) return Redirect(returnUrl);
                    else return RedirectToAction("Index", "Home");
                }
                else
                    ModelState.AddModelError("", "用户名或密码错误！");
            }
            return View();
        }

        public ActionResult SignOut()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("Index", "Home");
        }
    }
}
